package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.ArticleServiceClient;
import com.hxkj.domain.context.EnvironmentContextHolder;
import com.hxkj.domain.po.Article;
import com.hxkj.domain.po.Tags;
import com.hxkj.domain.po.WebsiteAddr;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

import static com.hxkj.client.service.taglib.config.LableConstant.CMS_ARTICLE_HOT;

/**
 * @ClassName HotArticleDirective 热门文章，及推荐级别
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/7/20 9:04
 * @Version 1.0
 */
@Component
@Log4j
public class HotArticleDirective extends AbstractDirective {

    @Autowired
    private ArticleServiceClient articleServiceClient;

    /**
     * 输入参数，分类ID字符串
     */
    public static final String SITE_ID = "siteId";

    /**
     * 输入参数，分类ID字符串
     */
    public static final String COLUMN_IDS = "columnIds";
    /**
     * 输入参数，分类ID
     */
    public static final String COLUMN_ID = "columnId";

    /**
     * 输入参数，是否排序,0：升序，1：降序
     */
    public static final String SORT = "sort";
    /**
     * 输入参数，获取参数条数
     */
    public static final String COUNT = "count";
    /**
     * 输入参数，获取参数条数
     */
    public static final String START = "start";

    /**
     * 输入参数，标题字数长度，多余的用"...."替代
     */
    public static final String TITLELEN = "titleLen";
    /**
     * 输入参数，文章推荐等级
     */
    public static final String LOCATION_LEVEL = "locationLevel";

    /**
     * 输入参数，是只查有图片的文章 0、为需要显示图片 1、为不需要显示图片
     */
    public static final String SHOW_IMG = "showImg";

    /**
     * 文章推荐、热门文章的标签名
     */
    public static final String HOT_ARTICLE = "articleList";


    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws
            TemplateException, IOException {
        env.getOut();
        try {
            Long siteId = super.getLong(SITE_ID, params) == null ? (Long) getCustomAttrbute(env, SITE_ID) : super.getLong(SITE_ID, params);
            //Mr.zheng:获取参数
            String columnIds = super.getString(COLUMN_IDS, params) == null ? "" : super.getString(COLUMN_IDS, params);
            //Mr.zheng:获取参数
            Long columnId = super.getLong(COLUMN_ID, params) == null ? null : super.getLong(COLUMN_ID, params);
            //Mr.zheng:默认根据降序排序
            String sort = super.getString(SORT, params) == null ? " update_time DESC ,heat DESC" : super.getString(SORT,
                    params);
            //Mr.zheng:默认取1条文章
            int start = super.getInt(START, params) == null ? 1 : super.getInt(START, params);
            //Mr.zheng:默认取5条文章
            int count = super.getInt(COUNT, params) == null ? 5 : super.getInt(COUNT, params);
            //Mr.zheng:默认取20字节
            int titleLen = super.getInt(TITLELEN, params) == null ? 20 : super.getInt(TITLELEN, params);
            //Mr.zheng:默认文章推荐等级不设置则为-1
            int locationLevel = super.getInt(LOCATION_LEVEL, params) == null ? -1 : super.getInt(LOCATION_LEVEL, params);
            //Mr.zheng:默认为-1、不需要带图片
            int showImg = super.getInt(SHOW_IMG, params) == null ? -1 : super.getInt(SHOW_IMG, params);

            String note = super.getNote(env);

            String userToken = super.getUserToken(env);
            if (StringUtils.isNotBlank(columnIds)) {
            }
            if (columnId != null) {

            }
            //Mr.zheng:封装查询参数
            Article article = new Article();
            article.setSort(sort);
            article.setSiteId(siteId);
            article.setCount(count);
            article.setTitleLen(titleLen);
            article.setLocationLevel(locationLevel);
            article.setShowImg(showImg);
            article.setStart(start - 1);
            if (StringUtils.isNotBlank(columnIds)) {
                article.setColumnIds(columnIds);
            } else if (columnId != null) {
                article.setColumnId(columnId);
            }
            List<Article> articleList;
            articleList = articleServiceClient.getArticleListByParam(article);

            WebsiteAddr websiteAddr = getWebSiteAddr(siteId);

            if (StringUtils.isNotBlank(note)) {//模板可视化
                for (Article arc : articleList) {
                    arc.setManuscriptPath(websiteAddr.getIpAdd() + arc.getManuscriptPath());
                }
            }else {
                Map<String, Object> enviroment = EnvironmentContextHolder.getEnvironment();
                Map<Long, String> siteCtxMap = (Map<Long, String>) enviroment.get("siteCtxMap");
                // 静态文件文章链接加前缀
                for (Article item : articleList) {
                    String urlContext = siteCtxMap.get(siteId);
                    if(StringUtils.isNotBlank(urlContext)) {
                        item.setManuscriptPath(urlContext + item.getManuscriptPath());
                    }
                }
            }
            env.setVariable(HOT_ARTICLE, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(articleList));

            if (body != null) {
                if (StringUtils.isEmpty(note)) {
                    body.render(env.getOut());
                } else {
                    Map<String, String> maps = new LinkedHashMap<>();
                    maps.put(CMS_ARTICLE_HOT, "");
                    maps.put(SITE_ID, String.valueOf(super.getLong(SITE_ID, params)));
                    maps.put(COLUMN_IDS, String.valueOf(super.getString(COLUMN_IDS, params)));
                    maps.put(COLUMN_ID, String.valueOf(super.getLong(COLUMN_ID, params)));
                    maps.put(SORT, super.getString(SORT, params));
                    maps.put(START, String.valueOf(super.getInt(START, params)));
                    maps.put(COUNT, String.valueOf(super.getInt(COUNT, params)));
                    maps.put(TITLELEN, String.valueOf(super.getInt(TITLELEN, params)));
                    maps.put(LOCATION_LEVEL, String.valueOf(super.getInt(LOCATION_LEVEL, params)));
                    maps.put(SHOW_IMG, String.valueOf(super.getInt(SHOW_IMG, params)));
                    try {
                        super.print(body, maps, env, userToken, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                throw new RuntimeException("热门文章所在模板至少要加一个空格");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
